<!--
 * @Author: xuzehan h935351619@163.com
 * @Date: 2024-11-28 14:14:41
 * @LastEditors: xuzehan h935351619@163.com
 * @LastEditTime: 2024-12-04 16:50:06
 * @FilePath: \qlck-vue\src\views\ErrorRate\ErrorRateTest.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form-model layout="inline" ref="ruleForm" :model="ruleForm" :rules="rules111">
        <a-row>
          <!-- <a-col :md="4" :sm="12">
            <a-form-model-item label="测试模式" prop='testMode'>
              <j-dict-select-tag v-model="ruleForm.testMode" placeholder="请选择测试模式" dictCode="test_mode_db" />
            </a-form-model-item>
          </a-col>
          <a-col :md="4" :sm="12" v-if='ruleForm.testMode == "导频模式"'>
            <a-form-model-item label="通道号" prop='startTdh'>
              <a-input-number v-model="ruleForm.startTdh" style="width:100%" placeholder="请输入1-380" :min='1'
                :max='380'></a-input-number>
            </a-form-model-item>
          </a-col> -->
          <a-col :md="4" :sm="12">
            <a-form-model-item label="通道类型" prop="aisleType">
              <j-dict-select-tag
                @change="onChange"
                v-model="ruleForm.aisleType"
                placeholder="请选择通道类型"
                dictCode="aisle_type"
              />
            </a-form-model-item>
          </a-col>
          <!-- <a-col :md="4" :sm="12" v-if="ruleForm.aisleType == '1'">
            <a-form-model-item label="通道号" prop="startTdh">
              <a-input-number
                v-model="ruleForm.startTdh"
                style="width:100%"
                placeholder="请输入1-380"
                :min="1"
                :max="380"
              ></a-input-number>
            </a-form-model-item>
          </a-col>
          <a-col :md="4" :sm="12" v-else-if="ruleForm.aisleType == '2'">
            <a-form-model-item label="通道号" prop="startTdh">
              <a-input-number
                v-model="ruleForm.startTdh"
                style="width:100%"
                placeholder="请输入1-33"
                :min="1"
                :max="33"
              ></a-input-number>
            </a-form-model-item>
          </a-col> -->
          <a-col :md="4" :sm="12" v-if="ruleForm.aisleType == '1'">
            <a-form-model-item label="符号速率" prop="symbolRate">
              <j-dict-select-tag v-model="ruleForm.symbolRate" placeholder="请选择符号速率" dictCode="symbol_rate_db" />
            </a-form-model-item>
          </a-col>
          <a-col :md="4" :sm="12" v-if="ruleForm.aisleType == '2'">
            <a-form-model-item label="符号速率" prop="symbolRate">
              <a-input
                disabled
                v-model="ruleForm.symbolRateInt"
                style="width:100%"
                placeholder="请输入符号速率"
              ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="3">
            <span style="float: left;overflow: hidden;margin-left: 10px;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="handleStart()" :disabled="disabled">开始</a-button>
              <a-button type="primary" style="margin-left: 8px" @click="handleStop" :disabled="!disabled"
                >停止</a-button
              >
              <!-- <a-button type="primary"
                style="margin-left: 8px" @click="handleReset">复位</a-button> -->
            </span>
          </a-col>
          <a-col :span="3" v-if="showSpin">
            <a-spin />
          </a-col>
          <a-col :span="24" style="margin-bottom: 10px;">
            <span style="color:#fff;font-size: 16px;">
              <span style="color:red;margin-right: 3px;">*</span
              >说明：国内测试1-380号通道，特征码不超过218字节；国际测试1-33号通道，特征码不超过649字节
            </span>
          </a-col>
          <!-- <a-col :span="12">
            <span style="color:#fff;float: left;">
              说明：国内测试1-380号通道，特征码不超过218字节；国内测试1-33号通道，特征码不超过649字节
            </span>
          </a-col> -->
          <!-- <a-col :md="6" :sm="12" v-if='ruleForm.testMode == "轮询模式"'> -->
          <a-col :span="24">
            <a-form-model-item label="特征码" prop="errorSourceData">
              <a-textarea
                placeholder="请输入特征码(0~F的16进制数)"
                v-model="ruleForm.errorSourceData"
                :auto-size="{ minRows: 1, maxRows: 3 }"
              ></a-textarea>
            </a-form-model-item>
          </a-col>
          <!-- <a-col :span="12">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="handleStart()" :disabled="disabled">开始</a-button>
              <a-button type="primary" style="margin-left: 8px" @click="handleStop" :disabled="!disabled">停止</a-button>
            </span>
          </a-col> -->
        </a-row>
      </a-form-model>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!-- <a-button type="primary" icon="download" @click="handleExportXls('帧信息')">导出</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel">
            <a-icon type="delete" />删除
          </a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px">
          批量操作
          <a-icon type="down" />
        </a-button>
      </a-dropdown> -->
    </div>
    <!-- table区域-begin -->
    <div style="margin-top: 35px;">
      <!-- <div style="color:#fff">
        说明：国内测试1-380号通道，特征码不超过218字节；国内测试1-33号通道，特征码不超过649字节。
      </div> -->
      <!-- <a-divider orientation="left" style="color:#fff">测试结果（总帧数/误码数/误码率）</a-divider> -->
      <a-descriptions :column="4">
        <a-descriptions-item label="总帧数">
          {{ desData.frameTotal }}
        </a-descriptions-item>
        <a-descriptions-item label="总误码数">
          {{ desData.errorFrameTotal }}
        </a-descriptions-item>
        <a-descriptions-item label="总误码率">
          {{ Number(desData.errorFramePercentage * 100).toFixed(2) }}%
        </a-descriptions-item>
        <a-descriptions-item label="测试时间" v-if="desData.testTime">
          {{ desData.testTime }}
        </a-descriptions-item>
      </a-descriptions>
      <div class="tdsjxs">
        <div v-for="i in listData" :key="i.tdh" style="width:20%;border:1px solid;padding:10px;height:70px">
          <div>{{ i.tdh }}</div>
          <div>({{ i.frameTotal }}/{{ i.errorFrameTotal }}/{{ Number(i.errorFramePercentage * 100).toFixed(2) }}%)</div>
        </div>
      </div>
    </div>
  </a-card>
</template>

<script>
import { getAction, httpAction } from '@/api/manage'

export default {
  name: 'PollingTest',
  components: {},
  data() {
    let validateErrorSourceData = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入误码源数据'))
        return
      }

      // if (value.length % 2 != 0) {
      //   callback(new Error('请确保输入长度为偶数'))
      //   return
      // }

      // if (!/^[0-9A-F]+$/.test(value)) {
      //   callback(new Error('请确保输入数据时16进制字符串(全大写)'))
      //   return
      // }

      // 根据通道类型决定最大长度
      const maxLen = this.ruleForm.aisleType == 2 ? 649 : 218

      if (value.length > maxLen) {
        const tip = this.ruleForm.aisleType == 2 ? '国际通道特征码不能超过 649 字符' : '国内通道特征码不能超过 218 字符'
        callback(new Error(tip))
        return
      }
      // const maxByte = this.ruleForm.aisleType == 2 ? 649 : 218
      // const actualByte = byteLen(value)

      // if (actualByte > maxByte) {
      //   const tip = this.ruleForm.aisleType == 2 ? '国际通道特征码不能超过 649 字节' : '国内通道特征码不能超过 218 字节'
      //   callback(new Error(tip))
      //   return
      // }

      callback()
    }
    return {
      description: '误码率测试页面',
      rules111: {
        testMode: [{ required: true, message: '请选择测试模式', trigger: 'blur' }],
        startTdh: [{ required: true, message: '请输入通道号', trigger: 'blur' }],
        symbolRate: [{ required: true, message: '请选择符号速率', trigger: 'change' }],
        errorSourceData: [
          { validator: validateErrorSourceData },
          { required: true, message: '请输入误码源数据', trigger: 'blur' }
        ],
        aisleType: [{ required: true, message: '请选择通道类型', trigger: 'blur' }]
      },
      url: {
        list: '/frameInfo/nmcFrameInfo/list',
        add: '/plan/qlTestPlan/add',
        addGj: '/plan/qlTestPlan/addGj',
        stop: '/plan/qlTestPlan/stopTestPlan',
        reset: '/Reset',
        getRunningTestPlan: '/plan/qlTestPlan/getRunningTestPlan',
        getPassagewayTestPlanStatistics: '/dcpr/dcprPassagewayHistoryInfo/getPassagewayTestPlanStatistics'
      },
      desData: {
        frameTotal: 0,
        errorFramePercentage: 0,
        errorFrameTotal: 0,
        testTime: null
      },
      disabled: false,
      ruleForm: {
        testMode: '轮询模式',
        startTdh: '',
        symbolRate: '300',
        symbolRateInt: '200',
        errorSourceData: '',
        aisleType: '',
        errorSourceDataInt: ''
      },
      testId: '',
      timer: null,
      timer1: null,
      listData: [
        // {tdh:1,frameTotal:20,errorFrameTotal:2,errorFramePercentage:10},
      ],
      showSpin: false
    }
  },
  created() {
    // this.getListData();
    this.loadData()
  },
  mounted() {
    document.addEventListener('visibilitychange', this.handleVisibilityChange)
    // window.onfocus = this.startTimer(); // 页面聚焦时开始定时任务
    // window.onblur = this.stopTimerFun(); // 页面失去焦点时停止定时任务
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  destroyed() {
    this.stopTimerFun()
  },
  methods: {
    handleVisibilityChange() {
      if (document.visibilityState === 'visible') {
        // 页面变为可见，重新开始定时器
        this.startTimer()
      } else if (document.visibilityState === 'hidden') {
        // 页面变为不可见，清除定时器
        this.stopTimerFun()
      }
    },
    getRunningTestPlan() {
      getAction(this.url.getRunningTestPlan)
        .then(res => {
          if (res.success) {
            if (res.result) {
              this.disabled = true
              this.testId = res.result.id
              this.ruleForm = Object.assign({}, res.result)
            } else {
              this.disabled = false
              this.testId = ''
              this.stopTimerFun()
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(error => {
          console.error('Promise rejected:', error)
          // 这里可以处理错误，或者再次抛出错误
        })
    },
    loadData() {
      console.log('777')
      //获取上一次的测试数据
      let listData = JSON.parse(localStorage.getItem('listData') || '[]')
      let desData = JSON.parse(localStorage.getItem('desData') || '{}')
      let ymdh = localStorage.getItem('ymdh')
      if (ymdh && listData && desData) {
        this.desData = desData
        this.listData = listData
        this.desData.testTime = ymdh
      }
      getAction(this.url.getRunningTestPlan)
        .then(res => {
          if (res.success) {
            if (res.result) {
              this.disabled = true
              this.testId = res.result.id
              this.ruleForm = Object.assign({}, res.result)
              if (!this.ruleForm.errorSourceData) {
                //生成一个长度为218的特征码
                // this.ruleForm.errorSourceData = this.generateRandomString()
                this.ruleForm.errorSourceData = this.generateHexString()
              }
              this.getPassagewayInfo()
              this.startTimer()
            } else {
              this.disabled = false
              // this.ruleForm.errorSourceData = this.generateRandomString()
              this.ruleForm.errorSourceData = this.generateHexString()
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(error => {
          console.error('Promise rejected:', error)
          // 这里可以处理错误，或者再次抛出错误
        })
    },
    startTimer() {
      //每5秒刷新一次通道测试信息
      if (!this.testId) return
      if (this.timer) clearInterval(this.timer)

      this.timer = setInterval(() => {
        this.getPassagewayInfo()
        this.getRunningTestPlan()
      }, 9000)
    },
    stopTimerFun() {
      clearInterval(this.timer)
    },
    getPassagewayInfo() {
      //获取通道信息
      getAction(this.url.getPassagewayTestPlanStatistics, { planId: this.testId })
        .then(res => {
          if (res.success) {
            if (res.result) {
              //先清除上一次的缓存结果
              localStorage.removeItem('listData')
              localStorage.removeItem('desData')

              //每5秒刷新一次通道测试信息
              let ymdh = localStorage.getItem('ymdh')
              this.listData = [...res.result.passagewayItemVoList]
              this.desData = Object.assign({}, res.result)
              this.desData.testTime = ymdh
              //将查询结果缓存到本地
              localStorage.setItem('listData', JSON.stringify(this.listData))
              localStorage.setItem('desData', JSON.stringify(this.desData))
            } else {
            }
          } else {
            this.$message.error(res.message)
          }
        })
        .catch(error => {
          console.error('Promise rejected:', error)
          // 这里可以处理错误，或者再次抛出错误
        })
    },
    handleStart() {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let data = {
            endTdh: '',
            startTdh: this.ruleForm.startTdh,
            symbolRate: this.ruleForm.symbolRate,
            testMode: this.ruleForm.testMode,
            errorSourceData: this.ruleForm.errorSourceData
          }
          const ymdh = new Date()
            .toLocaleString('zh-CN', {
              year: 'numeric',
              month: '2-digit',
              day: '2-digit',
              hour: '2-digit',
              minute: '2-digit',
              hour12: false
            })
            .replace(/\//g, '-')
          console.log('this.ruleForm', this.ruleForm)
          if (this.ruleForm.testMode == '导频模式') {
            data.endTdh = this.ruleForm.startTdh
          } else if (this.ruleForm.testMode == '轮询模式') {
            if (this.ruleForm.aisleType == 1) {
              data.startTdh = 1
              data.endTdh = 380
              this.showSpin = true
              httpAction(this.url.add, data, 'post')
                .then(res => {
                  if (res.success) {
                    this.$message.success(res.message)
                    localStorage.removeItem('ymdh')
                    localStorage.setItem('ymdh', ymdh)
                    this.desData.testTime = ymdh
                    this.ruleForm.aisleType = ''
                    this.loadData()
                  } else {
                    this.$message.error(res.message)
                    this.ruleForm.aisleType = ''
                  }
                })
                .finally(() => {
                  this.showSpin = false
                })
            }

            if (this.ruleForm.aisleType == 2) {
              data.symbolRate = '200'
              data.startTdh = 401
              data.endTdh = 433
              this.showSpin = true
              httpAction(this.url.addGj, data, 'post')
                .then(res => {
                  if (res.success) {
                    this.$message.success(res.message)
                    this.ruleForm.aisleType = ''
                    localStorage.removeItem('ymdh')
                    localStorage.setItem('ymdh', ymdh)
                    this.desData.testTime = ymdh
                    this.loadData()
                  } else {
                    this.$message.error(res.message)
                    this.ruleForm.aisleType = ''
                  }
                })
                .finally(() => {
                  this.showSpin = false
                })
            }
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleStop() {
      getAction(this.url.stop, { id: this.testId }).then(res => {
        this.stopTimerFun()
        if (res.success) {
          this.$message.success(res.message)
          this.testId = ''
          this.stopTimerFun()
          this.disabled = false
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleReset() {
      getAction(this.url.reset).then(res => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    getListData() {
      getAction(this.url.list).then(res => {
        this.listData = res.result.records
      })
    },
    onChange(key) {
      this.ruleForm.symbolRateInt = '200'
      this.ruleForm.aisleType = key
      // this.ruleForm.errorSourceData = this.generateRandomString()
      this.ruleForm.errorSourceData = this.generateHexString()
    },
    byteLen(str) {
      let len = 0
      for (let i = 0; i < str.length; i++) {
        let code = str.charCodeAt(i)
        if (code <= 0x007f) {
          len += 1 // 1 字节
        } else if (code <= 0x07ff) {
          len += 2 // 2 字节
        } else if (code <= 0xffff) {
          len += 3 // 3 字节
        } else {
          len += 4 // 4 字节（极少见）
        }
      }
      return len
    },
    // generateRandomString() {
    //   let length = this.ruleForm.aisleType == 2 ? 649 : 218
    //   const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    //   let result = ''
    //   const charsLength = chars.length

    //   for (let i = 0; i < length; i++) {
    //     result += chars.charAt(Math.floor(Math.random() * charsLength))
    //   }

    //   return result
    // },
    generateHexString() {
      // 根据type确定长度
      // const length = this.ruleForm.aisleType == 2 ? 649 : 218
      const length = 218
      // 生成指定长度的16进制字符串
      let hexString = ''
      for (let i = 0; i < length; i++) {
        // 生成0-F的随机16进制字符
        const randomHex = Math.floor(Math.random() * 16)
          .toString(16)
          .toUpperCase()
        hexString += randomHex
      }

      return hexString
    }
  }
}
</script>
<style scoped lang="less">
@import '~@assets/less/common.less';

.tdsjxs {
  display: flex;
  flex-wrap: wrap;
  // padding:20px;
  height: calc(100vh - 300px);
  overflow-y: scroll;
  // border: 1px solid;
}
</style>
